<?php

namespace App\Http\Controllers\Admin;

use App\Exports\QhUserExport;
use App\Exports\QhUserExport2;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\UserRequest;
use App\Models\CourseColumn;
use App\Models\LearnVideo;
use App\Models\Order;
use App\Models\User;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Facades\Excel;
use Psr\SimpleCache\InvalidArgumentException;

class UserController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = User::filter(request()->all())->orderByDesc('id')->paginate(request('perPage', 10));

        return $this->restful($list);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param UserRequest $request
     * @return JsonResponse|object
     */
    public function store(UserRequest $request)
    {
        $params = $request->validated();

        $user = User::create($params);

        return $this->restful($user);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param UserRequest $request
     * @param int $id
     * @return JsonResponse|object
     */
    public function update(UserRequest $request, int $id)
    {
        $params = $request->validated();
        $result = User::where('id', $id)->update($params);

        return $this->restful($result);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     */
    public function destroy(int $id)
    {
        $result = User::where('id', $id)->delete();

        return $this->restful($result);
    }

    /**
     * 修改状态
     * @param Request $request
     * @return JsonResponse|object
     * @throws \RedisException
     */
    public function changeStatus(Request $request) {
        $id = $request->input('id');
        $status = $request->input('status');

        $user = User::where('id', $id)->first();
        if ($status != 'normal' && $status != 'ban') return $this->Restful(null, false, '状态值不正确');

        // 清掉刷题限制
        if ($user->status == 'ban' && $status == 'normal') {
            try {
                $fullKey = 'UserLearn';
                $hashKey = 'userId='.$user->id;
                $cacheValue = Redis::client()->hDel($fullKey, $hashKey);
            } catch (InvalidArgumentException $e) {
            }
        }

        $user->status = $status;
        $user->save();


        return $this->Restful();
    }

    /**
     * @return JsonResponse|object
     * @throws Exception
     */
    public function userExport() {
        $users = User::orderBy('id')->get();

        if (count($users) < 1)  throw new Exception('用户为空');
        $filename = '用户列表'.time().'.xlsx';

        try {
            // $result = Excel::store(new QhUserExport(['users' => $users]), $filename, 'public');
            $result = Excel::store(new QhUserExport2(['users' => $users]), $filename, 'public');
            if (!$result) throw new Exception('导出失败');
        }catch (Exception $e) {
            throw new Exception('导出失败');
        }

        return $this->restful([
            'filename' => $filename,
            'url' => \Storage::disk('public')->url($filename)
        ]);
    }

    /**
     * 获取用户详情
     * @param $id
     * @return JsonResponse|object
     * @throws Exception
     */
    public function getUserInfo($id)
    {
        $user = User::find($id);
        if (!$user) throw new Exception('用户不存在');

        $data['base'] = Arr::only($user->toArray(), [
            'id',
            'nickname',
            'avatar',
            'mobile',
            'status',
            'province',
            'createtime'
        ]);

        if (!empty($data['base']['avatar']) && mb_strcut($data['base']['avatar'], 0, 4) != 'http') {
            $data['base']['avatar'] = config('filesystems.disks.aliyun.domain').$data['base']['avatar'];
        }
        $data['base']['statusText'] = USER_STATUS[$data['base']['status']];
        $data['base']['createtime'] = $data['base']['createtime'] ? Carbon::createFromTimestamp($data['base']['createtime'])->format('Y-m-d H:i:s') : '-';

        // 网课
        // 应该读取用户课程的：兑换记录/课程订单、今日学习+累计时长+学习天数+完成课数+专栏总进度+单科进度+网课等相关数据，点击后可进入相关下单订单
        $data['netCourse']['learnVideos'] = LearnVideo::select([
            'learn_videos.*',
            'user_learn_video_logs.userId',
            'user_learn_video_logs.getAt',
            'user_learn_video_logs.getType',
            'user_learn_video_logs.isTry',
            'user_learn_video_logs.expireAt',
        ])
            ->join('user_learn_video_logs', 'learn_videos.id', '=', 'user_learn_video_logs.learnVideoId')
            ->where('user_learn_video_logs.userId', $user->id)
            //->where('user_learn_video_logs.isTry', 0)
            ->orderByDesc('user_learn_video_logs.getAt')
            ->get();
        foreach ($data['netCourse']['learnVideos'] as $item) {
            if ($item->expireAt) {
                if (Carbon::make($item->expireAt)->diffInYears(now()) > 90) $item->expireAt2 = '长期';
                else $item->expireAt2 = Carbon::make($item->expireAt)->format('Y-m-d');
            }
            $item->orderId = DB::table('tiku_order')->where('userId', $user->id)->where('relationId', $item->id)->where('type', 3)->value('id');
        }
        $courseColumnIds = \DB::table('user_course_column_buy_logs')->where('userId', $user->id)->pluck('dataId')->toArray();
        $data['netCourse']['courseColumns'] = CourseColumn::whereIn('id', $courseColumnIds)->get();
        foreach ($data['netCourse']['courseColumns'] as $item) {
            $userBuyLog = DB::table('user_course_column_buy_logs')->where('userId', $user->id)->where('dataId', $item->id)->first();
            if ($userBuyLog) {
                $userBuyLog->expireAt = getCourseColumnExpireAt($item);
                if (Carbon::make($userBuyLog->expireAt)->lt(now())) return null;
                if (Carbon::make($userBuyLog->expireAt)->diffInYears(now()) > 90) $userBuyLog->expireAt = '长期';
                else $userBuyLog->expireAt = $userBuyLog->expireAt->format('Y.m.d');
                $item->expireAt = $userBuyLog->expireAt;
                $item->getType = $userBuyLog->getType;
                $item->getTypeText = $userBuyLog->getType == 1 ? '购买' : '激活码';
                if ($userBuyLog->getType == 1) {
                    $item->orderId = DB::table('tiku_order')->where('userId', $user->id)->where('relationId', $item->id)->where('type', 4)->value('id');
                }
            }
        }
        //$data['netCourse']['courseColumnOrderIds'] = Order::where('userId', $user->id)->where('type', 4)->orderByDesc('id')->pluck('id')->toArray();
        //$data['netCourse']['courseColumnOrderIds'] = implode(',', $data['netCourse']['courseColumnOrderIds']);
        //$data['netCourse']['learnVideoOrderIds']
        //$data['netCourse']['courseColumnOrder'] = Order::where('userId', $user->id)->where('type', 4)->orderByDesc('id')->get();
        $data['netCourse']['stat'] = [
            'minuteOfToday' => $user->netCourseLearnOfLastTime ? (Carbon::make($user->netCourseLearnOfLastTime)->isToday() ? $user->netCourseLearnMinuteOfToday : 0) : 0,       // 今日学习分钟数
            'hourOfAll' => round($user->netCourseLearnMinute / 60),           // 总学习小时数
            'learnDays' => ($user->netCourseLearnMinute > 0 && round($user->netCourseLearnMinute / 60 / 24) < 1) ? 1 : round($user->netCourseLearnMinute / 60 / 24),           // 学习天数
            'learnSection' => $user->learnVideoSectionDoneCount,        // 已学小节
            'allSection' => $user->learnVideoSectionCount,          // 所有小节
        ];

        return $this->restful($data);
    }
}
